package com.mvp.lt.airlineview.record;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.google.vr.sdk.widgets.pano.VrPanoramaEventListener;
import com.google.vr.sdk.widgets.pano.VrPanoramaView;
import com.mvp.lt.airlineview.R;
import com.mvp.lt.airlineview.RxObservableTransformer;
import com.mvp.lt.airlineview.base.BaseActivity;
import com.mvp.lt.airlineview.record.event.RecordServiceEvent;
import com.mvp.lt.airlineview.record.event.RecordTimeEvent;
import com.mvp.lt.airlineview.utils.DateUtils;
import com.mvp.lt.airlineview.utils.FileUtils;
import com.mvp.lt.airlineview.utils.LogUtil;
import com.mvp.lt.airlineview.utils.ThreadUtil;
import com.mvp.lt.airlineview.utils.ToastUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * @author LiuTao
 * @description:
 * @date : 2021/3/10 10:42
 */
public class RecordServiceActivity extends BaseActivity {
    private boolean isRecording = false;
    private final String workMediaVideoPath = FileUtils.getDir("recordfile");
    private Disposable recordTimeDisposable;
    private TextView mTextView;

    public static void show(Context context) {
        Intent intent = new Intent(context, RecordServiceActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        ScreenRecorderUtils.getInstance().stopRecord();
        ScreenRecorderUtils.getInstance().stopRecprdSerVice(this);
    }

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_service);
        EventBus.getDefault().register(this);
        mTextView = findViewById(R.id.record_time);
        ScreenRecorderUtils.getInstance().initRecordService();
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.RECORD_AUDIO,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.FOREGROUND_SERVICE).subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            ScreenRecorderUtils.getInstance().initRecordService();
                        }
                    }
                });
    }

    public void startRecord(View view) {
        RecordingVideoPopupView recordingVideoPopupView = new RecordingVideoPopupView(this);
        recordingVideoPopupView.show();
        recordingVideoPopupView.setListener(new RecordingVideoPopupView.OnPopupListener() {
            @Override
            public void onStartRecord(int width, int height, boolean audio) {
                String videoName = System.currentTimeMillis() + "";
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    LogUtil.e("录屏服务", "=================onStartRecord==============="+width+"----"+height);
                    ScreenRecorderUtils.getInstance().startCustomRecord(RecordServiceActivity.this, width, height, workMediaVideoPath, videoName, audio);
                } else {
                    ToastUtils.showToast("手机系统低于5.0");
                }
            }
        });
    }

    public void stopRecord(View view) {
        stopRecordAndSaveData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.e("录屏服务", "=================onActivityResult===============");
        ScreenRecorderUtils.getInstance().onActivityResult(this, requestCode, resultCode, data);
    }

    private void stopRecordAndSaveData() {
        if (recordTimeDisposable != null) {
            recordTimeDisposable.dispose();
        }
        if (isRecording) {
            isRecording = false;
            ThreadUtil.getInstance().execute(new Runnable() {
                @Override
                public void run() {
                    ScreenRecorderUtils.getInstance().stopRecord();
                }
            });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void recordServiceEvent(RecordServiceEvent recordServiceEvent) {
        LogUtil.e("录屏服务", "==========recordServiceEvent=============");
        if (recordServiceEvent.isRecording()) {
            //开始录屏
            isRecording = true;
            Observable.interval(0, 1000, TimeUnit.MILLISECONDS)
                    .compose(RxObservableTransformer.transformer())
                    .subscribe(new io.reactivex.Observer<Long>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            recordTimeDisposable = d;
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(Long aLong) {
                            String time = DateUtils.getFormatHMS(aLong * 1000);
                            mTextView.setText(time);
                            EventBus.getDefault().post(new RecordTimeEvent(aLong * 1000));
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }

    }
}
